from fastapi import APIRouter, Request
from model import db
from model.user import regist,User,UserQuestion,UserCommit
from exception import JsonException
from model.user import User
from pydantic import BaseModel,Field
from controller.rtn import Rtn
from datetime import datetime
from model.config import get_config


router = APIRouter()

# chat 聊天
class registReq(BaseModel):
    code: str = Field(default="", description='code', min_length=1, max_length=200)

@router.post("/regist")
def regist1(request: Request, registReq: registReq):

    user =  regist(registReq.code)

    return Rtn(user)



# 修改用户信息
class infoReq(BaseModel):
    trueName: str = Field(default="", description='真实姓名', min_length=0, max_length=255)
    mobile: str = Field(default="", description='电话', min_length=11, max_length=11)
    address: str = Field(default="", description='地址', min_length=0, max_length=255)
    areaCode: str = Field(default="", description='地区代码', min_length=0, max_length=255)
    areaInfo: str = Field(default="", description='地区信息', min_length=0, max_length=1024)
    company: str = Field(default="", description='工作单位', min_length=0, max_length=255)

@router.post("/set_info")
def info(request: Request, infoReq: infoReq):
    user:User = request.state.userInfo

    with db.Session() as session:

        one = session.query(User).filter(
            User.id == user.id
        ).first()

        if one == None:
            raise JsonException("用户不存在", 400)
        
        if infoReq.trueName != "":
            one.trueName = infoReq.trueName

        if infoReq.mobile != "":
            one.mobile = infoReq.mobile

        if infoReq.address != "":
            one.address = infoReq.address
            
        if infoReq.areaCode != "":
            one.areaCode = infoReq.areaCode

        if infoReq.areaInfo != "":
            one.areaInfo = infoReq.areaInfo

        if infoReq.company != "":
            one.company = infoReq.company

        session.commit()

    return Rtn()



@router.get("/info")
def info(request: Request):

    user:User = request.state.userInfo
    now = datetime.now()

    conf = get_config()

    day_commit_limit = conf.day_commit_limit

    date_str = now.strftime('%Y-%m-%d')

    with db.Session() as session:

        # 用户今日提交次数
        query = session.query(UserCommit).filter(
            UserCommit.user_id == user.id,
            UserCommit.created_time >= date_str,
        )
        user_today_commit_count = query.count()

    
    return Rtn({
        "user":user,
        "day_commit_limit":day_commit_limit,
        "user_today_commit_count":user_today_commit_count,
        "user_point_count":user.true_question_count * conf.point_k,
    })